package com.dpwgc.demo.service;

import com.dpwgc.demo.config.SftpConfig;
import com.dpwgc.demo.mapper.AdminMapper;
import com.dpwgc.demo.mapper.LogMapper;
import com.dpwgc.demo.model.Admin;
import com.dpwgc.demo.model.Log;
import com.dpwgc.demo.utils.*;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipOutputStream;

@Service
public class AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    LogMapper logMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    ZipUtils zipUtils;

    @Autowired
    DateUtil dateUtil;

    @Value("${sftp.hostname}")
    String hostname;
    @Value("${sftp.port}")
    String port;
    @Value("${sftp.username}")
    String username;
    @Value("${sftp.password}")
    String password;
    @Value("${sftp.timeout}")
    String timeout;

    /**
     * 管理员登录
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public ResultUtil<Object> loginService(String username,String password){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        try{
            Admin admin = adminMapper.login(username,password);

            if(admin != null){

                /* 生成token,并将token存储于redis中，设置7200s过期时间 */
                String token = UUID.randomUUID().toString().replaceAll("-", "");
                redisUtil.set(admin.getId()+"", token,7200);

                resultUtil.setCode(200);
                resultUtil.setMsg("登录成功|token:"+token);
                resultUtil.setData(admin);
                return resultUtil;
            }
            else {

                resultUtil.setCode(100);
                resultUtil.setMsg("账户或密码错误");
                resultUtil.setData("err");
                return resultUtil;
            }
        }catch (Exception e){

            resultUtil.setCode(100);
            resultUtil.setMsg("登录失败");
            resultUtil.setData(e);
            return resultUtil;
        }
    }

    /**
     * 根据logUri获取访问记录列表
     * @param logUri 访问控制器路径
     * @return
     */
    public ResultUtil<Object> queryLogByUriService(String logUri,Integer startPage,Integer endPage){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        try{
            List<Log> logs = logMapper.queryLogByUri(logUri,startPage,endPage);

            resultUtil.setCode(200);
            resultUtil.setMsg("获取成功");
            resultUtil.setData(logs);
            return resultUtil;

        }catch (Exception e){

            resultUtil.setCode(100);
            resultUtil.setMsg("获取失败");
            resultUtil.setData(e);
            return resultUtil;
        }
    }

    /**
     * 获取文件列表
     * @param directory 文件目录
     * @return
     */
    public ResultUtil<Object> fileListService(String directory){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        SftpUtil sftpUtil = new SftpUtil(3, 6000);

        SftpConfig sftpConfig = new SftpConfig(hostname, Integer.parseInt(port), username, password, Integer.parseInt(timeout), directory);
        try {
            List<String> list = sftpUtil.listFiles(directory, sftpConfig);

            resultUtil.setCode(200);
            resultUtil.setMsg("操作成功");
            resultUtil.setData(list);
            return resultUtil;

        } catch (SftpException e) {
            resultUtil.setCode(100);
            resultUtil.setMsg("操作失败");
            resultUtil.setData(e);
            return resultUtil;
        }
    }

    /**
     * 删除文件
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     */
    public ResultUtil<Object> deleteFileService(String directory,String deleteFile){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        SftpUtil sftpUtil = new SftpUtil();

        SftpConfig sftpConfig = new SftpConfig(hostname, Integer.parseInt(port), username, password, Integer.parseInt(timeout), "/");
        ChannelSftp channelSftp = sftpUtil.connect(sftpConfig);

        sftpUtil.delete(directory,deleteFile,channelSftp);

        try {
            resultUtil.setCode(200);
            resultUtil.setMsg("操作成功");
            resultUtil.setData(dateUtil.getDateTime());
            return resultUtil;

        }catch (Exception e){

            resultUtil.setCode(100);
            resultUtil.setMsg("操作失败");
            resultUtil.setData(e);
            return resultUtil;
        }
    }

    /**
     * 压缩 zip
     * @param filePath  文件夹 全路径(例：/dp_cos/file/test/)
     * @param fileName  文件夹名称(例：test)
     * @param outPath   压缩文件保存路径(例：/dp_cos/file/zip/test.zip)
     */
    public ResultUtil<Object> zipFileService(String filePath, String fileName, String outPath) {

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        try {
            //创建Test.zip文件
            OutputStream is = new FileOutputStream(outPath);
            //检查输出流,采用CRC32算法，保证文件的一致性
            CheckedOutputStream cos = new CheckedOutputStream(is, new CRC32());
            //创建zip文件的输出流
            ZipOutputStream zos = new ZipOutputStream(cos);
            //需要压缩的文件或文件夹对象
            File file = new File(filePath);
            //压缩文件的具体实现函数
            boolean flag = zipUtils.zip(zos,file,filePath,fileName,outPath);

            if(!flag){
                resultUtil.setCode(100);
                resultUtil.setMsg("压缩失败");
                resultUtil.setData("压缩工具方法：zip报错");
                return resultUtil;
            }
            zos.close();
            cos.close();
            is.close();

            resultUtil.setCode(200);
            resultUtil.setMsg("压缩成功");
            resultUtil.setData(outPath);
            return resultUtil;

        } catch (Exception e) {

            resultUtil.setCode(100);
            resultUtil.setMsg("压缩失败");
            resultUtil.setData(e);
            return resultUtil;
        }
    }

    /**
     * 下载文件
     *
     * @param directory    下载目录
     * @param downloadFile 下载的文件
     * @param saveFile     存在本地的路径
     */
    /*
    public ResultUtil<Object> downloadFileService(String directory, String downloadFile, String saveFile){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        SftpUtil sftpUtil = new SftpUtil();

        SftpConfig sftpConfig = new SftpConfig(hostname, Integer.parseInt(port), username, password, Integer.parseInt(timeout), "/");
        ChannelSftp channelSftp = sftpUtil.connect(sftpConfig);

        sftpUtil.download(directory,downloadFile,saveFile,sftpConfig);

        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData(dateUtil.getDateTime());
        return resultUtil;
    }
     */
}
